<?php
/**
 * Desc:
 * User: hollowcg@foxmail.com
 * Date: 2019/5/25
 */

namespace app\common\model;


use think\Db;
use think\Model;
use think\Request;

class User extends Model
{


    /**
     * 获取分页数据
     * @param $data
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getDataArr($data){

        $where = [];

        if (!empty($data['username']))
            $where['a.username'] = ['like','%'.$data['username'].'%'];

        if (!empty($data['role_id']))
            $where['a.role_id'] = $data['role_id'];

        isset($data['page'])?$page = $data['page']:$page = 1;
        isset($data['limit'])?$limit = $data['limit']:$limit = 10;

        $sql = Db::name('user')->alias('a')
            ->join([
                ['userRole b','a.role_id = b.id','left']
            ])
            ->where($where);

        $data = $sql->field('a.*,b.name as role')
            ->order('a.id desc')
            ->limit(($page-1)*$limit,$limit)->select();

        if (!empty($data)){
            foreach ($data as $k=>$v){
                $data[$k]['password'] = encry_code($v['password'],'DECODE');
            }
        }
        $count = $sql->count();
        return apiResult($data,0,'',$count);
    }


    /**
     * 保存
     * @param $data
     * @param $id
     * @return array
     */
    public static function saveData($data,$id){

        $model = \model('user');

        $data['password'] = encry_code($data['password']);
        try{

            $validate = [
                'username|用户名'=>"unique:user"
            ];

            if (empty($id)){
                $result = $model->validate($validate)->allowField(true)->isUpdate(false)->save($data);
            }else{
                $result = $model->validate($validate)->allowField(true)->isUpdate(true)->save($data,['id'=>$id]);
            }

            if(false === $result){
                // 验证失败 输出错误信息
                return apiResult('',1,$model->getError());
            }

            return apiResult($model->getLastInsID(),0,'操作成功');

        }catch (\Exception $e){
            return apiResult('',1,$e->getMessage());
        }

    }

}